package com.css.fxfzaqbz.modules.data.repository.impl;


import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.modules.data.entity.ActiveFaultData;
import com.css.fxfzaqbz.modules.data.entity.HospitalData;
import com.css.fxfzaqbz.modules.data.entity.ImportantActivity;
import com.css.fxfzaqbz.modules.data.queryParams.ActiveFaultDataQueryParams;
import com.css.fxfzaqbz.modules.data.queryParams.HospitalDataQueryParams;
import com.css.fxfzaqbz.modules.data.repository.HospitalDataRepository;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class HospitalDataRepositoryImpl implements HospitalDataRepository {

    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public ActiveFaultData updateActiveFaultData(ActiveFaultData activeFaultData) {
//
//        String sql = "update sys_activefaultdata set afd_number = :afdNumber," +
//                " afd_name = :afdName, afd_length = :afdLength," +
//                " afd_newactivity = :afdNewactivity, afd_status = :afdStatus, " +
//                " afd_updatetime = :afdUpdatetime" +
//                " where afd_id = '"+activeFaultData.getAfdId()+"'" ;
//
//        SqlParameterSource source = new BeanPropertySqlParameterSource(activeFaultData);
//        //拿到新插入的主键值（i）
//        KeyHolder keyHolder = new GeneratedKeyHolder();
//        namedParameterJdbcTemplate.update(sql,source,keyHolder);
//        return activeFaultData;
//    }

    @Override
    @Transactional
    public HospitalData saveHospitalData(HospitalData hospitalData) {
        String sql = "insert into sys_hospital_data  (hd_id,hd_number,hd_longitude,hd_latitude,hd_name,hd_type,hd_peoNumber,hd_bed,hd_address,hd_status,create_time,update_time,create_user) values(:hdId,:hdNumber,:hdLongitude,:hdLatitude,:hdName,:hdType,:hdPeoNumber,:hdBed,:hdAddress,:hdStatus,:hdCreatetime,:hdUpdatetime,create_user)";

        SqlParameterSource source = new BeanPropertySqlParameterSource(hospitalData);
        //拿到新插入的主键值（i）
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int i = namedParameterJdbcTemplate.update(sql, source, keyHolder);
        return hospitalData;
    }

    @Override
    public Map<String,Object> getAllHospitalDataParams(HospitalDataQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select  h.* from sys_hospital_data h ");

        StringBuilder orderSql = new StringBuilder(" order by h.hd_number");

        StringBuilder whereSql = new StringBuilder(" where h.del_flag = '" + YNEnum.N.toString() + "'");

//        if (!PlatformObjectUtils.isEmpty(queryParams.getElevationBand()) ){
//            whereSql.append(" and e.elevation_band like '%" + queryParams.getElevationBand() + "%'");
//        }
//
//        if (!PlatformObjectUtils.isEmpty(queryParams.getElevationNodatavalue()) ){
//           whereSql.append(" and e.elevation_nodatavalue like '%" + queryParams.getElevationNodatavalue() + "%'");
//        }

        int firstIndex=(queryParams.getCurPage()-1) * queryParams.getPageSize();
        int lastIndex=queryParams.getCurPage() * queryParams.getPageSize();
        sql.append(whereSql).append(orderSql).toString();
        StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(HospitalData.class)).size();
        List<HospitalData> hospitalData = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(HospitalData.class));
        Map<String,Object> map=new HashMap();
        map.put("total",total);
        map.put("rows",hospitalData);
        return map;
    }

    @Override
    public HospitalData getHospitalDataById(String id) {
        String sql = "select * from sys_hospital_data where hd_id = '"+id+"'  and del_flag = '"+YNEnum.N+"'";
        HospitalData hospitalData = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(HospitalData.class));
        return hospitalData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHospitalDataById(List<String> ids, Timestamp timestamp) {
        String sql = "update sys_hospital_data set hd_status = '" + YNEnum.Y + "' , update_time = '"+timestamp+"' " + " where hd_id in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    @Override
    public List<HospitalData> getAll() {
        return jdbcTemplate.query("select * from sys_hospital_data where del_flag = '"+YNEnum.N+"'",new BeanPropertyRowMapper<>(HospitalData.class));
    }

    @Override
    public void importExcel(List<HospitalData> hospitalData) {
        jdbcTemplate.batchUpdate("insert into sys_hospital_data (hd_id,hd_number,hd_longitude,hd_latitude,hd_name,hd_type,hd_peo_number,hd_bed,hd_address,hd_status,hd_createtime)values(?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
            @Override
            public int getBatchSize() {
                return hospitalData.size();
            }
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1, hospitalData.get(i).getHdId());
                ps.setString(2,hospitalData.get(i).getHdNumber());
                ps.setFloat(3,hospitalData.get(i).getHdLongitude());
                ps.setFloat(4,hospitalData.get(i).getHdLatitude());
                ps.setString(5,hospitalData.get(i).getHdName());
                ps.setString(6,hospitalData.get(i).getHdType());
                ps.setString(7,hospitalData.get(i).getHdPeoNumber());
                ps.setString(8,hospitalData.get(i).getHdBed());
                ps.setString(9,hospitalData.get(i).getHdAddress());
                ps.setString(10,hospitalData.get(i).getDelFlag());
                java.sql.Date createtime = new java.sql.Date(hospitalData.get(i).getCreateTime().getTime()) ;
                ps.setDate(11,createtime);
            }
        });
    }

}
